﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TaoPortal.BusinessLogic.DTO;
using TaoPortal.BusinessLogic.Extensions;
using TaoPortal.DataAccess;
using TaoPortal.Entity;

namespace TaoPortal.BusinessLogic.Repository
{
    public class SimplePageRepository : BaseRepository
    {
        public SimplePageRepository(DataContext dbcontext)
        {
            db = dbcontext;
            AutoCommit = true;
        }

        public SimplePageRepository()
            : this(new DataContext())
        {

        }

        public PagedList<SimplePageList> GetSimplePageList(string pTitle, string pKey, DateTime? startDate, DateTime? endDate, int pageIndex, int pageSize)
        {
            var data = db.TP_SimplePage.OrderByDescending(x => x.CreateTime).Select(x => x);
            if (!string.IsNullOrEmpty(pTitle))
                data = data.Where(x => x.PTitle == pTitle);
            if (!string.IsNullOrEmpty(pKey))
                data = data.Where(x => x.PKey == pKey);
            if (startDate != null)
                data = data.Where(x => x.CreateTime >= startDate);
            if (endDate != null)
            {
                endDate = endDate.Value.AddDays(1);
                data = data.Where(x => x.CreateTime <= endDate);
            }
            return data.Select(x => new SimplePageList
            {
                ID = x.ID,
                PTitle = x.PTitle,
                PKey = x.PKey,
                CreateTime = x.CreateTime,
                PUrl = x.PUrl
            }).ToPagedList(pageIndex, pageSize);
        }

        public void AddSimplePage(TP_SimplePage sp)
        {
            db.TP_SimplePage.Add(sp);
            SaveChanges();
        }

        public void UpdateSimplePage(TP_SimplePage sp)
        {
            db.UpdateEntity(sp);
            SaveChanges();
        }

        public void DeleteSimplePage(string id)
        {
            db.Entry<TP_SimplePage>(new TP_SimplePage { ID = id }).State = System.Data.Entity.EntityState.Deleted;
            SaveChanges();
        }

        public TP_SimplePage GetSimplePageByID(string id)
        {
            return (from s in db.TP_SimplePage
                    where s.ID == id
                    select s).FirstOrDefault();
        }
    }
}
